<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/***********************************************************************\
| @package		Auth
| @author		Dennis T. Kaplan
| @copyright	Copyright (c) 2007, Dennis T. Kaplan
| @license		
| @link			http://www.pzzazz.com
| @since			Version 1.0
| @category		Libraries
\***********************************************************************/

class Auth 
{
	/*****************************************\
	| Auth Constructor
	\*****************************************/
    
    var $caller;
	
	function Auth()
	{
		$this->CI =& get_instance();
        $this->caller = False;
        log_message('debug', "Auth Library Class Initialized");
	}

	/*********************************************
	* Get alias and password
	*
	* @param varchar $alias
	* @param varchar $pass
	* @return object
	*/
	function Login($a, $p)
	{
		$where = array('Alias'=>$a, 'Password'=>$p);
		$this->db->where($where);
		$this->db->from('contact_user');
		$data = $this->db->get();
		unset($data->Pass);
      return $data; 
	}
	
	/**
	* Authorization Check
	**/
	function CheckTaMeR($key = FALSE)
	{
        $this->caller = 'CheckTaMeR';
		settype($account, "object");
		$groups = FALSE;
		
		if($this->CheckLogin() === TRUE) //Checking session here
		{
			$groups = $this->CI->session->userdata('groups');
		}
		else
		{
            $this->cookieLogin();
            $account = (object) $this->CI->session->userdata();
            $groups = $account->groups;
            $this->msg->setMsg('INFO: Login via cookie. Restricted access.');
		}
		
		if($groups === FALSE)
		{
			$this->LogOut();
		}
		
		if(($key !== FALSE) && ($groups !== FALSE)) 
		{
			$this->CheckAccess($key,$groups);
		}
	}
	
	function CheckAccess($key,$groups)
	{
        $key = explode(',', str_replace(' ', '', $key));
        $key[] = 1; # Admin has always access
        $groups = explode(',', str_replace(' ', '', $groups));
        foreach($key as $k)	{
            if (in_array($k, $groups)) {
                return TRUE;
            }
        }
		show_error("You don't have access to this area.");
	}
	
    
	function CheckLogin()
	{
		if($this->CI->session->userdata('uid') > 0){
            return TRUE;
		}else{
            if($this->caller === False){
                redirect('contact/login', 'location');
                //show_error("A login is requierd to access this area.");
            }else{
                return FALSE;
            }
		}
	}
	
    function cookieLogin()
    {
        $key = $this->getCookie();
        $this->CI->db->select('cookie, uid, people_id, org_id, Alias,  dgroup, groups, timezone, IP, status');
        $this->CI->db->from('contact_user');
        $this->CI->db->where('cookie', $key);
        $query = $this->CI->db->get();
        if($query->num_rows() > 0){
            $row = $query->row_array();
            $this->CI->session->set_userdata($row);
        }else{
            redirect('/contact/login/', 'location');
        }
    }
    
    
    function LogOut()
	{
        if ($this->CI->session->userdata('uid') > 0){
            $this->CI->session->sess_destroy();
            $this->delCookie();
            redirect('/', 'location');
        }else{
            show_error("You are not logged in.");
        }

	}
    
	function cfgCookie() {
		$c = array(
			'name'   => 'AuthTaMeRSave',
			'domain' => '', //'.'.$_SERVER["HTTP_HOST"],
			'path'   => '/',
			);
		return $c;
	}
	
	/**************************************************\
	| If Post save is checked this will be called to 
	| create a cookie!
	\**************************************************/
	function addCookie() 
	{
		// Create a unique key
		$uid = $this->CI->session->userdata('uid');
		$key = md5(uniqid(mt_rand(), true));
		$ip = $this->CI->fun->getip();
		// Add key to session
		$sess = array(
			'cookie' => $key,
			'IP'  => $ip
			);
		$this->CI->session->set_userdata($sess);
		
		$cookie = $this->cfgCookie();
		extract($cookie, EXTR_OVERWRITE);
		$expire = time()+60*60*24*90;
		setcookie($name, $key, $expire, $path, $domain, FALSE);
		
		$data = array(
			'cookie' => $key,
			'IP' => $ip
			);
		$this->CI->db->where('uid', $uid);
		$this->CI->db->update('contact_user', $data);
	}
    
    
	function getCookie()
	{
        $cookie = $this->cfgCookie();
		$name = $this->CI->input->cookie($cookie['name']);
        
		if($name !== FALSE)
		{
			return $name;
		}
		else
		{
			return FALSE;
		}
	}
	
	function delCookie()
	{
		$cookie = $this->getCookie();
		if($cookie !== FALSE)
		{
			$cookie = $this->cfgCookie();
			extract($cookie, EXTR_OVERWRITE);
			unset($cookie);
			$value = '';
			$expire = time()-60*60*24*90;
			setcookie($name, $value, $expire, $path, $domain, TRUE);
			$cookie['cookie'] = '';
			unset($cookie);
		}
	}
    function ActivationEmail($id, $alias, $email, $key)
    {
		 $host = $_SERVER['HTTP_HOST'];
		 $url = site_url('auth/activation/'.$id.'/'.$key);
		 
		 $subject= "Your " .$host. " activaten key.";
		 $message = 
		 "Welcome " .$alias. " to " .$host. "\r\n\r\n"
		 ."To activate your account, please click "
		 ."on the following link and enter your Activation code:\r\n\r\n"
		 ."Activation code: " .$key. "\r\n\r\n"
		 .$url."\r\n\r\n\r\n"
		 ."If you have received this mail in error, "
		 ."you do not need to take any action to cancel the account. \r\n"
		 ."The account has not be created, "
		 ."the information we have will be deleted from our server periodically, "
		 ."and you will not receive any further emails. \r\n\r\n"
		 ."Thank you for using " .$host. ".\r\n\r\n"
		 ."This is a post-only mailing. "
		 ."Replies to this message are not monitored or answered.";
		 
		 $this->fun->SendEmail($email, $subject , $message);
    }

    function SendPass($alias, $email, $pass)
    {
		 $host = $_SERVER['HTTP_HOST'];
		 
		 $subject= "Your " .$host. " login info.";
		 $message = 
		 "Welcome back to " .$host. "\r\n\r\n"
		 ."You already have an account with us "
		 ."following is your login information:\r\n\r\n"
		 ."Alias: " .$alias. "\r\n"
		 ."Password: " .$pass. "\r\n"
		 ."http://".$host. "\r\n\r\n\r\n"
		 ."If you have received this mail in error, "
		 ."you do not need to take any action. \r\n"
		 ."You will not receive any further emails. \r\n\r\n"
		 ."Thank you for using " .$host. ".\r\n\r\n"
		 ."This is a post-only mailing. "
		 ."Replies to this message are not monitored or answered.";
		 
		 $this->fun->SendEmail($email, $subject , $message);
    }


}


?>
